package linkedList;

/**
 * 前置类
 *
 * @author yyz
 * @create 2023-11-07 9:15
 */
public class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        ListNode p = this;
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        while (p != null) {
            if (p.next != null) {
                sb.append(p.val).append(",");
            }else
                sb.append(p.val);
            p = p.next;
        }
        sb.append("]");

        return sb.toString();
    }

    /**
     * 创建链表并批量添加元素
     * @param elements 要添加的元素数组
     * @return 添加元素后的链表头节点
     */
    public static ListNode of(int... elements) {
        if (elements == null || elements.length == 0) {
            return null;
        }
        ListNode head = new ListNode(elements[0]);
        ListNode curr = head;
        for (int i = 1; i < elements.length; i++) {
            ListNode newNode = new ListNode(elements[i]);
            curr.next = newNode;
            curr = curr.next;
        }
        return head;
    }
}
